﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace CommonHelper
{
    public class ImageHelper
    {
        public static BitmapImage ConvertIndexed8bppToBitmapImage(byte[] pixelData, int width, int height)
        {
            // 创建一个具有 Format8bppIndexed 像素格式的 Bitmap
            Bitmap sourceBitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);

            // 获取 Bitmap 的 BitmapData 结构
            BitmapData data = sourceBitmap.LockBits(new System.Drawing.Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);

            // 将 pixelData 写入 Bitmap
            Marshal.Copy(pixelData, 0, data.Scan0, pixelData.Length);

            // 解锁位图数据
            sourceBitmap.UnlockBits(data);

            // 创建一个 WriteableBitmap 来装载原始 Bitmap
            WriteableBitmap writeableBitmap = new WriteableBitmap(sourceBitmap);

            // 创建一个 BitmapImage 并从 WriteableBitmap 加载
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = new MemoryStream(writeableBitmap.PixelBuffer);
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.EndInit();

            return bitmapImage;
        }
    }
}
